#!/usr/bin/env python
# -*- coding:utf8 -*-
# uncompyle6 version 2.15.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Jul  1 2017, 13:36:56) 
# [GCC 4.4.6 20110731 (Red Hat 4.4.6-4)]
# Embedded file name: ./esb/components/bk/apis/fta/imap_relay.py
# Compiled at: 2017-11-16 15:44:28
from django import forms
import arrow
from common.constants import API_TYPE_OP
from common.forms import BaseComponentForm
from components.component import Component
from .toolkit import tools, configs

class ImapRelay(Component):
    """[FTA] 外网请求代理
    
    {% block api_doc %}
    
    描述
    ~~~~
    
    参数说明
    ~~~~~~~~
    
    {{ common_args_desc }}
    
    其他参数
    
    ===============  ======  ========  ===========================================
    参数名称         必须    类型      参数说明
    ===============  ======  ========  ===========================================
    method           Y       string    请求方法（GET, POST)
    url              Y       int       请求URL
    kwargs           N       kwargs    其他requests支持的参数
    ===============  ======  ========  ===========================================
    
    请求参数示例
    ~~~~~~~~~~~~
    
    .. code:: json
    
        {
            "app_id": "46",
            "method": "GET",
            "url": 'http',
            "data": '',
        }
    
    结果说明
    ~~~~~~~~
    
    .. code:: json
    
        {
            "result": true,
            "code": "00",
            "message": "",
            "data": ''
        }
    
    {% endblock %}
    """
    sys_name = configs.SYSTEM_NAME
    api_type = API_TYPE_OP

    class Form(BaseComponentForm):
        app_id = forms.CharField(label=u'业务ID', required=True)
        email = forms.CharField(label=u'邮箱地址', required=True)
        password = forms.CharField(label=u'邮箱密码', required=True)
        imap_host = forms.CharField(label=u'imap协议地址', required=True)
        imap_port = forms.IntegerField(label=u'imap协议端口', required=True)
        secure = forms.BooleanField(label=u'imap是否开启SSL', required=False)
        charset = forms.CharField(label=u'字符编码', required=False)
        unseen = forms.BooleanField(label=u'未阅读', required=False)
        before = forms.CharField(label=u'在之前', required=False)
        since = forms.CharField(label=u'在开始', required=False)
        size_limit = forms.IntegerField(label=u'大小限制', required=False)
        sent_from = forms.CharField(label=u'来源', required=False)
        sent_to = forms.CharField(label=u'Sent To', required=False)
        subject = forms.CharField(label=u'Title', required=False)
        index = forms.IntegerField(label=u'分页index', required=False)
        limit = forms.IntegerField(label=u'分页limit', required=False)

        def clean_before(self):
            if not self.data.get('before'):
                return ''
            try:
                return arrow.get(self.data['before'])
            except Exception as error:
                raise forms.ValidationError('before datetime parser error: %s' % error)

        def clean_since(self):
            if not self.data.get('since'):
                return ''
            try:
                return arrow.get(self.data['since'])
            except Exception as error:
                raise forms.ValidationError('since datetime parser error: %s' % error)

    def handle(self):
        email = self.form_data['email']
        password = self.form_data['password']
        imap_host = self.form_data['imap_host']
        imap_port = self.form_data['imap_port']
        secure = self.form_data.get('secure', False)
        client = tools.IMAPClient(email, password, imap_host, imap_port, secure=secure)
        charset = self.form_data.get('charset', 'utf-8')
        unseen = self.form_data.get('unseen')
        before = self.form_data.get('before')
        since = self.form_data.get('since')
        size_limit = self.form_data.get('size_limit', 204800)
        sent_from = self.form_data.get('sent_from')
        sent_to = self.form_data.get('sent_to')
        subject = self.form_data.get('subject')
        index = self.form_data.get('index')
        limit = self.form_data.get('limit')
        result = client.request(charset, unseen, before, since, size_limit, sent_from, sent_to, subject, index, limit)
        self.response.payload = result
